# -*- coding:utf-8 -*-
import sys

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from faker import Faker

from Util import config


class Browser(object):
	driver = None

	def __init__(self):
		self.userAgent = self.user_agent()

	def getDriver(self):
		return self.driver

	def user_agent(self):
		fake = Faker()
		browserType = config.globalBrowserConf.browserType
		try:
			userAgent = eval(f"fake.{browserType}()")
		except AttributeError:
			from Util import logger
			logger.error(f"目前只支持chrome、firefox浏览器，请检查全局配置中浏览器类型")
			logger.warning(f"由于浏览器类型配置错误，默认使用chrome浏览器")
			userAgent = fake.chrome()
		return userAgent


class Chrome(Browser):

	def __init__(self, system):

		super(__class__, self).__init__()

		self.chrome_options = Options()
		self.chrome_options.add_argument(f'User-Agent={self.userAgent}')
		if config.globalBrowserConf.isHeadLess:
			self.chrome_options.add_argument('--headless')
		if system in ["windows", 'macOS']:
			self.driver = webdriver.Chrome(options=self.chrome_options)
		elif system == "linux":
			self.chrome_options.add_argument('--no-sandbox')
			self.chrome_options.add_argument('--disable-dev-shm-usage')
			self.driver = webdriver.Chrome(options=self.chrome_options)
		self.driver.maximize_window()


class Firefox(Browser):

	def __init__(self, system):
		super(__class__, self).__init__()
		if system == "windows":
			self.driver = webdriver.Firefox(service_log_path=f"{config.rootPath}/Log/otherLogs/geckodriver.log")


class DriverFactory(object):
	platform = {
		"win32": "windows",
		"linux": "linux",
		"darwin": "macOS"
	}

	def get_driver(self, browser=None):
		browser = browser or config.globalBrowserConf.browserType
		currentPlatform = sys.platform
		if browser == "chrome":
			return Chrome(self.platform.get(currentPlatform)).getDriver()
		elif browser == "firefox":
			return Firefox(self.platform.get(currentPlatform)).getDriver()
		else:
			raise Exception("please input 'chrome' or 'firefox'")


driverFactory = DriverFactory()

if __name__ == '__main__':

	driver = DriverFactory().get_driver()
	print(driver)
	driver.get("http://192.168.2.15")
	driver.close()
	driver.quit()
